<?php

class ArticleController extends BaseController
{

    public function init()
    {
        parent::init();
        $this->req = $this->getRequest();
        /* Initialize action controller here */
    }

    public function indexAction()
    {

    }

    public function latestReleaseListAction()
    {
        $this->view->title="最新发布";
        $uid = $this->user_id;
        $active = new \Base\Rest();
        $req = array(
            'uid'=>$uid,
            'status'=>\Orm\Article\ArticleClass::STATUS_ISSUED
        );
        $rest_res = $active->get('ArticleList',false,$req);
        if ($rest_res->isSuccess()) {
            $res = $rest_res->getResponse();
            $article_list = $this->object2array($res);
            foreach ($article_list as $key => $value){
                $long_time = $this->time_tranx($value['insert_time']);
                $article_list[$key]['long_time'] = $long_time;
            }
            $this->view->article_list = $article_list;
        } else {
            $this->view->article_list = array();
        }
    }


    /**
     * object转数组
     * @param $object
     * @return mixed
     */
    private function object2array(&$object) {
        $object =  json_decode( json_encode( $object),true);
        return  $object;
    }

    private function time_tranx($the_time){
        $now_time = date("Y-m-d H:i:s",time());
        $now_time = strtotime($now_time);
        $show_time = strtotime($the_time);
        $dur = $now_time - $show_time;
        if($dur < 0){
            return $the_time;
        }else{
            if($dur < 60){
                return $dur.'秒前';
            }else{
                if($dur < 3600){
                    return floor($dur/60).'分钟前';
                }else{
                    if($dur < 86400){
                        return floor($dur/3600).'小时前';
                    }else{
                        if($dur < 259200){ //3天内
                            return floor($dur/86400).'天前';
                        }else{
                            return $the_time;
                        }
                    }
                }
            }
        }
    }

    /**
     * 分享
     * @return array
     */
    public function shareAction()
    {
        $url = "http://www.sg.com/active/index";
        $uid = $this->user_id;
        $active = new \Base\Rest();
        $req = array('url'=>$url,'uid'=>$uid);
        $rest_res = $active->get('share',false,$req);
        $res = $rest_res->getResponse();
        $result = $this->object2array($res);
        try{
            return Response::Success($result,'SUCCESS');
        }catch (\Exception $e){
            return Response::Error(0,'ERROR');
        }
    }

    /**
     * 详情
     */
    public function detailAction()
    {
        $this->view->title="文章详情";
        $id = $this->req->get('id');
        if ($id == false ) {
            exit('缺少文章id');
        }
        $req = array('uid'=>$this->user_id); // todo user
        $rest = new \Base\Rest();
        $res = $rest->get('Article',$id,$req);
        $data = array(
            'article_id'=>$id
        );
        $post = array(
            'payload' => base64_encode(http_build_query($data))
        );
        $browse_res = $rest->post('Browse',$req,$post);
        if ($res->isSuccess() == false ) {exit('未找到此文章');}
        if ($browse_res->isSuccess() == false ) {exit('服务器内部错误');}
        $this->view->info = $res->getResponse();
        $this->view->preview = false;

    }

    /**
     * 发布
     */
    public function publishAction()
    {
        $this->view->title="发布";
        if ($this->req->isPost() == false ) {Response::Error(500,'非法请求');}
        $id = $this->req->getPost('id');
        if ($id == false ) {
            exit('缺少文章id');
        }
        $req = array('uid'=>$this->user_id); // todo user
        $rest = new \Base\Rest();
        $post_data = array(
            'status'=>\Orm\Article\ArticleClass::STATUS_ISSUED,
        );
        $post = array('payload'=>base64_encode(http_build_query($post_data)));
        $res = $rest->put('Article',$id,$req,$post);
        if ($res->isSuccess() == false ) {exit('未找到此文章');}
        $this->view->info = $res->getResponse();
    }

    public function editAction()
    {
        $this->view->title="我要发布";
        $id = $this->req->get('id');
        if ($id == false ) {
            exit('缺少文章id');
        }
        $req = array('uid'=>$this->user_id); // todo user
        $rest = new \Base\Rest();
        $res = $rest->get('Article',$id,$req);
//        var_dump($res);exit;
        if ($res->isSuccess() == false ) {exit('未找到此文章');}
        $this->view->info = $res->getResponse();
        $this->view->id = $id;
        $this->view->oss_url_path = \Util\Config::get('url_path','Oss');
        $this->view->oss_dir = \Util\Config::get('dir','Oss');
        $this->view->allowed_image_type = count(\Util\Config::get('allowed_image_type','Oss')) ? \Util\Config::get('allowed_image_type','Oss') : array();
        $this->view->allowed_video_type = count(\Util\Config::get('allowed_video_type','Oss')) ? \Util\Config::get('allowed_video_type','Oss') : array();
        $this->view->allowed_audio_type = count(\Util\Config::get('allowed_audio_type','Oss')) ? \Util\Config::get('allowed_audio_type','Oss') : array();
        $this->view->allowed_image_size = \Util\Config::get('allowed_image_size','Oss');
        $this->view->allowed_video_size = \Util\Config::get('allowed_video_size','Oss');
        $this->view->allowed_audio_size = \Util\Config::get('allowed_audio_size','Oss');
    }

    public function addContentAction()
    {
        if ($this->req->isPost() == false ) {Response::Error(500,'非法请求');}
        $article_id = $this->req->getPost('article_id');
        if ($article_id == false ) {Response::Error(500,'文章id不能为空');}
        $type = $this->req->getPost('type');
        if ($type == false ) {Response::Error(500,'文章类型不能为空');}
        $content = $this->req->getPost('content');
        $sort = $this->req->getPost('sort');
        $req = array(
            'uid'=>$this->user_id
        );
        $data = array(
            'article_id' => $article_id,
            'type' => $type,
            'content' => $content,
            'sort' => $sort,
        );
        $post = array(
            'payload' => base64_encode(http_build_query($data))
        );
        $rest = new \Base\Rest();
        $res = $rest->post('ArticleContent',$req,$post);

        if ($res->isSuccess()) {
            Response::Success($res->getResponse());
        } else {
            Response::Error(500,$res->getErrorMessage());
        }
    }

    public function updateContentAction()
    {
        if ($this->req->isPost() == false ) {Response::Error(500,'非法请求');}
        $id = $this->req->getPost('id');
        if ($id == false ) {Response::Error(500,'内容id不能为空');}
        $article_id = $this->req->getPost('article_id');
        if ($article_id == false ) {Response::Error(500,'文章id不能为空');}
        $type = $this->req->getPost('type');
        if ($type == false ) {Response::Error(500,'文章类型不能为空');}
        $content = $this->req->getPost('content');
        $sort = $this->req->getPost('sort');
        $req = array(
            'uid'=>$this->user_id
        );
        $data = array(
            'article_id' => $article_id,
            'type' => $type,
            'content' => $content,
            'sort' => $sort,
        );
        $post = array(
            'payload' => base64_encode(http_build_query($data))
        );
        $rest = new \Base\Rest();
        $res = $rest->put('ArticleContent',$id,$req,$post);

        if ($res->isSuccess()) {
            Response::Success($res->getResponse());
        } else {
            Response::Error(500,$res->getErrorMessage());
        }
    }

    public function deleteContentAction()
    {
        if ($this->req->isPost() == false ) {Response::Error(500,'非法请求');}
        $id = $this->req->getPost('id');
        if ($id == false ) {Response::Error(500,'内容id不能为空');}
        $req = array(
            'uid'=>$this->user_id
        );
        $rest = new \Base\Rest();
        $res = $rest->delete('ArticleContent',$id,$req,array());
        if ($res->isSuccess()) {
            Response::Success($res->getResponse());
        } else {
            Response::Error(500,$res->getErrorMessage());
        }
    }

    public function previewAction()
    {
        $id = $this->req->get('id');
        if ($id == false ) {Response::Error(500,'内容id不能为空');}

        $req = array('uid'=>$this->user_id); // todo user
        $rest = new \Base\Rest();
        $res = $rest->get('Article',$id,$req);
        if ($res->isSuccess() == false ) {exit('未找到此文章');}
        $this->view->info = $res->getResponse();
        $this->view->preview = true;
        $this->render('detail');
    }
    /*点赞*/
    public function fabulousAction(){
        if ($this->req->isPost() == false ) {Response::Error(500,'非法请求');}
        $article_id = $this ->req->getPost('article_id');
        $data = array(
            'type'=>'fabulous',
            'article_id'=>$article_id
        );
        $req = array(
            'uid'=>$this->user_id
        );
        $post = array(
            'payload' => base64_encode(http_build_query($data))
        );
        $rest = new \Base\Rest();
        $res = $rest->post('Fabulous',$req,$post);

        if ($res->isSuccess()) {
            Response::Success($res->getResponse());
        } else {
            Response::Error(500,$res->getErrorMessage());
        }
    }
    /*取消点赞*/
    public function cancelFabulousAction()
    {
        if ($this->req->isPost() == false ) {Response::Error(500,'非法请求');}

        $fabulous_id = $this ->req->getPost('fabulous_id');

        $data = array(
          'type'=>'calloff',
          'fabulous_id'=>$fabulous_id,
          'article_id'=>$fabulous_id
        );
        $req = array();
        $post = array(
            'payload' => base64_encode(http_build_query($data))
        );
        $rest = new \Base\Rest();
        $res = $rest->post('Fabulous',$req,$post);

        if ($res->isSuccess()) {
            Response::Success($res->getResponse());
        } else {
            Response::Error(500,$res->getErrorMessage());
        }
    }

    public function ossiniAction()
    {
        $id = \Util\Config::get('id', 'Oss');
        $key = \Util\Config::get('key', 'Oss');
        $host = \Util\Config::get('url_path', 'Oss');
        $callbackUrl = \Util\Config::get('callback_url', 'Oss');

        $callback_param = array('callbackUrl' => $callbackUrl,
            'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}&type=${x:type}&article_id=${x:article_id}&product_id=${x:product_id}',
            'callbackBodyType' => "application/x-www-form-urlencoded");
        $callback_string = json_encode($callback_param);

        $base64_callback_body = base64_encode($callback_string);
        $now = time();
        $expire = 30; //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问
        $end = $now + $expire;
        $expiration = $this->gmt_iso8601($end);
        $dir = \Util\Config::get('dir', 'Oss');

        //最大文件大小.用户可以自己设置
        $condition = array(0 => 'content-length-range', 1 => 0, 2 => 1048576000);
        $conditions[] = $condition;

        //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
        $start = array(0 => 'starts-with', 1 => '$key', 2 => $dir);
        $conditions[] = $start;


        $arr = array('expiration' => $expiration, 'conditions' => $conditions);
        //echo json_encode($arr);
        //return;
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

        $response = array();
        $response['accessid'] = $id;
        $response['host'] = $host;
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        $response['callback'] = $base64_callback_body;
        //这个参数是设置用户上传指定的前缀
        $response['dir'] = $dir;
        exit(json_encode($response));
    }

    private function gmt_iso8601($time)
    {
        $dtStr = date("c", $time);
        $mydatetime = new DateTime($dtStr);
        $expiration = $mydatetime->format(DateTime::ISO8601);
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);
        return $expiration . "Z";
    }

}



